import uuid

from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, JSON
from sqlalchemy.orm import relationship

from db.base import Base
from db.models.base import GUID, BaseDatabaseModel
from db.models.user import User
from db.repository.user import db_get_user_group_ids


class KnowledgeBase(BaseDatabaseModel, Base):
    __tablename__ = "knowledge_bases"

    id = Column(GUID(), primary_key=True, index=True, default=uuid.uuid1)
    name = Column(String(200), index=True)

    is_delete = Column(Boolean, default=False, index=True)
    kb_type = Column(String(255), default=False, index=True, comment="1:知识问答文件/2:双控文件/3:应急预案文件/4:事故案例文件")

    # owner = relationship('User', backref='knowledge_bases')
    owner = Column(Integer, ForeignKey('users.id'))
    group_ids = Column(JSON, nullable=True, default=[])  # 存储可以访问的用户组ID列表，以逗号分隔

    # 这里可以定义一个方法来检查用户是否有权限访问知识库
    def check_permission(self, user, user_groups):
        if self.owner == user.id:
            return True
        if any(group_id in self.group_ids for group_id in user_groups):
            return True
        return False

    def __repr__(self):
        return f"<KnowledgeBase(title={self.name}, owner_id={self.owner})>"

    def to_json(self):
        return {
            "id": str(self.id),
            "name": self.name,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "updated_time": self.updated_time.strftime("%Y-%m-%d %H:%M:%S"),
            "group_ids": self.group_ids,
            "kb_type": self.kb_type
        }

    def get_id(self):
        return str(self.id)

    def check_permit(self, user: User, user_groups=None):
        if self.owner == user.id or user.check_superman_role():
            return True
        if user_groups is None:
            user_groups = db_get_user_group_ids(user)
        if len(set(user_groups).intersection(set(self.group_ids))) == 0:
            return False
        return True


class File2Knowledge(BaseDatabaseModel, Base):
    __tablename__ = "file_2_knowledge"

    id = Column(GUID(), primary_key=True, index=True, default=uuid.uuid1)
    file_id = Column(String(64), comment="文件id(字符串，兼容files/dc_files)")
    knowledge_id = Column(GUID(), ForeignKey('knowledge_bases.id'), comment="知识库id")


class RecommendQuestion(BaseDatabaseModel, Base):
    __tablename__ = "recommend_question"

    id = Column(GUID(), primary_key=True, index=True, default=uuid.uuid1)
    knowledge_id = Column(GUID(), ForeignKey('knowledge_bases.id'), comment="知识库id")
    question = Column(String(255), comment="推荐问题")
    is_delete = Column(Boolean, default=False, index=True)

    def to_dict(self):
        return {
            "id": str(self.id),
            "knowledge_id": str(self.knowledge_id),
            "question": self.question,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "updated_time": self.updated_time.strftime("%Y-%m-%d %H:%M:%S"),
        }
